package zisu.netty.practice.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @Desc: ""
 * @Author: caixiang
 * @DATE: 2020/8/4 9:38
 */
public class MyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String res = new String(buffer, StandardCharsets.UTF_8);
        System.out.println("客户端接收到消息："+res);
        System.out.println("客户端接收到的消息数量"+ (++count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("进入异常 ："+cause.getMessage());
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //ping相当于是一个死循环
        ping(ctx.channel());
        //使用客户端发送10条数据 hello，server 带编号。
        for(int i=0;i<10;i++){
            ByteBuf buf = Unpooled.copiedBuffer("hello,server" + i+" ", StandardCharsets.UTF_8);
            ctx.writeAndFlush(buf);
        }
    }

    private void ping(Channel channel) {
        int second = Math.max(1, 10);
        System.out.println("next heart beat will send after " + second + "s.");
        ScheduledFuture<?> future = channel.eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                if (channel.isActive()) {
                    System.out.println("sending heart beat to the server...");
                    ByteBuf buf = Unpooled.copiedBuffer("ping", StandardCharsets.UTF_8);
                    channel.writeAndFlush(buf);
                } else {
                    System.err.println("The connection had broken, cancel the task that will send a heart beat.");
                    channel.closeFuture();
                    throw new RuntimeException();
                }
            }
        }, second, TimeUnit.SECONDS);

        future.addListener(new GenericFutureListener() {
            @Override
            public void operationComplete(Future future) throws Exception {
                if (future.isSuccess()) {
                    //这里回调的作用是 让future.run()重复执行，因为channel.eventLoop().schedule()只执行一次
                    ping(channel);
                }
            }
        });
    }

}
